<?php

class user_ajax extends AjaxPage
{	  
	var $output = "";
	var $access_level = 2;
	
  	function pre_process()
	// do things which may result in page redirections, terminations, etc
	// when making your own ALWAYS call 
	//		if (!parent::pre_process()) return false;
	// before doing anything
	// if the user fails authorization return false;
	// failure to follow this instructions will break your page
	{
		if (!parent::pre_process()) return false;
		
		switch (@$_REQUEST['action'])
		{			
			case 'listusers':
			case 'countusers':
				break;	
			
			case 'change_access':
				if (@empty($_REQUEST['user_id']))
					return array('status' => false, 
								'msg' => "A user_id is required and no user_id was specified.");
				if (@empty($_REQUEST['access_level']))
					return array('status' => false, 
								'msg' => "An access_level is required and no access_level was specified.");
				break;	
	
			default:
				return array('status' => false, 
								'msg' => "An unsupported ajax request was received in user_ajax: \"" . @$_REQUEST['action'] . "\"");
		}
			
		return true;
	}
	
	function page_do()
	{
		parent::page_do();	
		
		switch (@$_REQUEST['action'])
		{
			case 'change_access':
				@$this->app->sess->change_user_access($_REQUEST['user_id'], $_REQUEST['access_level']);
				$this->output = "{ \"success\": 1, \"msg\": \"success\" }";
				break;
			
			case 'listusers':
				$start = ifemptyuse(@$_REQUEST['start'], 0);
				$end = ifemptyuse(@$_REQUEST['end'], 50);
				$users = $this->app->sess->get_users($start, $end);
				//$sql =	"SELECT user_id,username,realname,email,access_level FROM `users`";
				$json_users = array();
				foreach ($users as $u)
				{
					$cur_json = "{";
					$cur_json .= "\"user_id\": " . $u['user_id'] . ",";
					$cur_json .= "\"username\": \"" . addslashes($u['username']) . "\",";
					$cur_json .= "\"realname\": \"" . addslashes($u['realname']) . "\",";
					$cur_json .= "\"email\": \"" . addslashes($u['email']) . "\",";
					$cur_json .= "\"access_level\": " . $u['access_level'];
					$cur_json .= "}";
					$json_users[] = $cur_json;
				}
				
				$this->output = "{ \"success\": 1, \"msg\": \"success\", \"users\": [\n" . implode(",\n", $json_users) . "], \"cur_access_level\": " . $this->app->sess->access_level . " }";
				break;
			
			case 'countusers':
				$cnt = $this->app->sess->user_count();
				$this->output = "{ \"success\": 1, \"msg\": \"success\", \"num_users\": $cnt }";
				break;
			
		}
	}	  
}

?>